package com.example.workrecord.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: AliYunOssPrivateUtil
 * @Description: 阿里云私有OSS工具类
 * @Author: Wei
 * @Date: 2018/8/13 18:43
 * @Version: 1.0
 */
public class AliYunOssPrivateUtil {

    private AliYunOssPrivateUtil() {
        throw new IllegalStateException("Utility class");
    }

    private static final Logger logger = Logger.getLogger(AliYunOssPrivateUtil.class);

    private static String endpoint = "172.21.248.70";
    private static String accessKeyId = "GnCsIyQsNpxfuEec";
    private static String accessKeySecret = "bewNkxmFVCJ6NLWIihk49xl4jalwSF";
    private static String bucketName = "csj";

    /**
     * 以文件流方式上传
     *
     * @param multipartFile
     * @return
     */
    public static String fileUpload(MultipartFile multipartFile) {
        String newName = "";
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
            listBucketsRequest.setMaxKeys(500);
            String ext = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf('.'));
            newName = System.currentTimeMillis() + Tools.getRandomNum3() + ext;
            // 上传文件流
            ossClient.putObject(bucketName, newName, multipartFile.getInputStream());
            // 设置URL过期时间为10年。
            Date expiration = new Date(System.currentTimeMillis() + 1000 * 3600 * 24 * 365 * 10);
            System.err.println(System.currentTimeMillis());
            System.err.println(expiration.getTime());
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(bucketName, newName, expiration);
            System.err.println("URL:" + url.toString());
            System.err.println("URL-FILE:" + url.getFile());
            System.err.println("http://220.191.216.241:8080" + url.getFile());
            newName="http://220.191.216.241:8080" + url.getFile();
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (Exception ce) {///
            logger.error(ce.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return newName;
    }

    /**
     * 下载文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public static void fileDowload(HttpServletRequest request, HttpServletResponse response, String filePath,String name) throws IOException {
        String fileName = "file_name";
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucketName, filePath);

        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = ossObject.getObjectContent().read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.flush();
        byte[] data = bos.toByteArray();

        String key = name != null && !"".equals(name.trim()) ? name:filePath;
        // 中文文件名支持
        // 替换空格，否则firefox下有空格文件名会被截断,其他浏览器会将空格替换成+号
        String encodedFileName = key.trim().replaceAll(" ", "_");

        String agent = request.getHeader("User-Agent");
        boolean isMSIE = ((agent != null) && (agent.toUpperCase().indexOf("MSIE") != -1));

        if (isMSIE) {
            encodedFileName = URLEncoder.encode(encodedFileName, "UTF-8");
        } else {
            encodedFileName = new String(key.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
        // 关闭client
        ossClient.shutdown();
    }

    /**
     * 下载文件到本地
     *
     * @throws Exception
     */
    public static void fileDowloads(String filePath, String fileName, String dowloadPath) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName, filePath), new File(dowloadPath + File.separator + fileName));
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 删除单个文件
     *
     * @param key
     */
    public static void deleteObject(String key) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除Object
            ossClient.deleteObject(bucketName, key);
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (Exception ce) {
            logger.error(ce.getMessage());
        } finally {
            ossClient.shutdown();
        }

    }

    /**
     * 删除多个文件
     *
     * @param keys
     */
    public static void deleteObjects(List<String> keys) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除Objects
            ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (Exception ce) {
            logger.error(ce.getMessage());
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 获取文件访问路径
     *
     * @param key    文件对应key
     * @param second 过期时间s
     * @return
     */
    public static String getUrl(String key, int second) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 设置URL过期时间
        Date expiration = new Date(System.currentTimeMillis() + second * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest;
        generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }

}
